//
//  LLComposeController.m
//  Weibo
//
//  Created by 李灵斌 on 15-2-4.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "LLComposeController.h"
#import "LLComposeTextView.h"
#import "LLComposeToolbar.h"
#import "LLComposeHttpTool.h"
#import "LLComposeRequestPara.h"
#import "LLComposeRequestResult.h"
#import "LLPicViewController.h"
#import "LLComposePhoto.h"
@interface LLComposeController ()<UITextViewDelegate, LLComposeToolbarDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, LLComposePhotoDelegate>
@property (nonatomic, weak) LLComposeTextView *inputView;
@property (nonatomic, weak) LLComposeToolbar *toolbar;
@property (nonatomic, weak) LLComposePhoto *photoView;
@property (nonatomic, strong) NSMutableArray *photos;
@end

@implementation LLComposeController

- (NSMutableArray *)photos{
    
    if (!_photos) {
        
        _photos = [NSMutableArray array];
    }
    return _photos;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置导航条
    [self setupNav];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建inputView
    [self setupInputView];
    
    // 创建photo容器
    [self setupComposePhoto];
    
    // 设置辅助键盘toolBar
    [self setupToolbar];
    
}


- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    self.navigationItem.rightBarButtonItem.enabled = self.inputView.text.length >0;
    
    [self.inputView becomeFirstResponder];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 键盘弹出隐藏通知监听方法
- (void)show:(NSNotification *)note{
    
    // UIKeyboardAnimationDurationUserInfoKey
    // UIKeyboardFrameEndUserInfoKey
    CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat time = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:time animations:^{
       
#warning toobarl的y值向上为负值
        self.toolbar.transform = CGAffineTransformMakeTranslation(0, -rect.size.height);
    }];
}

- (void)hide:(NSNotification *)note{
    
    CGFloat time = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:time animations:^{
        self.toolbar.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - 自定义控件
- (void)setupComposePhoto{
    
    LLComposePhoto *photoView = [[LLComposePhoto alloc] init];
    photoView.frame = CGRectMake(0, 200, self.view.width, self.view.height);
    photoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:photoView];
    photoView.delegate = self;
    self.photoView = photoView;
}

- (void)setupToolbar{
    
    LLComposeToolbar *toolbar = [[LLComposeToolbar alloc] init];
    toolbar.width = self.view.width;
    toolbar.height = 44;
    toolbar.y = self.view.height - toolbar.height;
    toolbar.delegate = self;
    [self.view addSubview:toolbar];
    self.toolbar = toolbar;
    
    // 监听键盘的弹出，通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(show:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hide:) name:UIKeyboardWillHideNotification object:nil];
}


/**
 *   创建inputView
 */
- (void)setupInputView{
    
    LLComposeTextView *inputView = [[LLComposeTextView alloc] init];
    inputView.width = self.view.width;
    inputView.height = self.view.height;
    inputView.backgroundColor = [UIColor grayColor];
    inputView.placeHolder = @"分享新鲜事...";
    inputView.delegate = self;
    inputView.alwaysBounceVertical = YES;
    [self.view addSubview:inputView];
    self.inputView = inputView;

}



/**
 *  设置导航条
 */
- (void)setupNav{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancle)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
}

/**
 *  取消
 */
- (void)cancle{
    
    [self.inputView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  发送
 */
- (void)send{
    
    if (self.inputView.text.length > 0 && self.photos.count == 0) {
        
        // 发送文字到微博
        [self sendStatusWithOutImage];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    if (self.photos.count >= 1 && self.inputView.text.length >0) {
        
        [self sendStatusWithImage];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - sendStatusWithOutImage
- (void)sendStatusWithOutImage{
    
    LLComposeRequestPara *para = [[LLComposeRequestPara alloc] init];
    para.status = self.inputView.text;
    [LLComposeHttpTool postPara:para success:^(LLComposeRequestResult *result) {
        
        [SVProgressHUD showSuccessWithStatus:@"发送成功"];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"发送失败"];
    }];
}

- (void)sendStatusWithImage{
    
    LLComposeRequestPara *para = [[LLComposeRequestPara alloc] init];
    para.status = self.inputView.text;
    [LLComposeHttpTool postPara:para body:^(id<AFMultipartFormData> formdata) {
        NSData *data = UIImagePNGRepresentation([self.photos firstObject]);
        [formdata appendPartWithFileData:data name:@"pic" fileName:@"xx00" mimeType:@"image/png"];
    } success:^(LLComposeRequestResult *result) {
        [SVProgressHUD showSuccessWithStatus:@"发送成功"];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"发送失败"];
    }];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    
    self.navigationItem.rightBarButtonItem.enabled = textView.text.length > 0;
    if (textView.text.length) {
        
        self.inputView.placeHolder = nil;
    } else {
        
        self.inputView.placeHolder = @"分享新鲜事...";
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    
    [self.inputView resignFirstResponder];
}

#pragma mark - LLComposeToolbarDelegate
- (void)composeToobarDidClickBtn:(LLComposeToolbar *)toolbar type:(LLComposeToolbarType)type{
    
    switch (type) { // 照相机
        case LLComposeToolbarButtonTypeCamera:{
            [self setupCamera];
        }
            break;
        // 照片
        case LLComposeToolbarButtonTypePicture:{
            [self setupPic];
        }
            break;
        case LLComposeToolbarButtonTypeMention:
            
            break;
        case LLComposeToolbarButtonTypeEmotion:
            
            break;
        case LLComposeToolbarButtonTypeTrend:
            
            break;
        default:
            break;
    }
}

#pragma mark - 选择toolbar 上不同的按钮点击事件
/**
 *  UIImagePickerControllerSourceTypePhotoLibrary,
    UIImagePickerControllerSourceTypeCamera,
    UIImagePickerControllerSourceTypeSavedPhotosAlbum
 */
- (void)setupCamera{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
//    UIImagePickerController *camera = [[UIImagePickerController alloc] init];
}

- (void)setupPic{
    if (![LLPicViewController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary | UIImagePickerControllerSourceTypeSavedPhotosAlbum]) return;
    
//    UIViewController *vc = [[UIViewController alloc] init];
    LLPicViewController *pic = [[LLPicViewController alloc] init];
  
    [self presentViewController:pic animated:YES completion:nil];
    
    pic.delegate = self;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
   UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    [self.photos addObject:originalImage];
    self.photoView.photos = self.photos;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)composePhoto:(LLComposePhoto *)photo{
    
    [self setupPic];
}

@end
